﻿namespace AddressBook.Business.Contact
{
	#region "Using Statements"
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;

	using Csla;
	using Csla.Data;
	#endregion

	[Serializable]
	public class ContactAddresses : BusinessListBase<ContactAddresses, ContactAddress>
	{
		#region "Business Methods"

		public ContactAddress GetItem(Int32 addressId)
		{
			foreach (ContactAddress address in this)
			{
				if (address.AddressId == addressId)
				{
					return address;
				}
			}

			return null;
		}

		public void Add(Int32 addressTypeId)
		{
			if (!(Contains(addressTypeId)))
			{
				ContactAddress resource = ContactAddress.NewAddress(addressTypeId);
				this.Add(resource);
			}
			else
			{
				throw new InvalidOperationException("Contact already has an address of that type");
			}
		}

		public void Add(String address1, String address2, String city, Int32 stateProvinceId, String postalCode, Int32 addressTypeId)
		{
			if (!(Contains(addressTypeId)))
			{
				ContactAddress resource = ContactAddress.NewAddress(address1, address2, city, stateProvinceId, postalCode, addressTypeId);
				this.Add(resource);
			}
			else
			{
				throw new InvalidOperationException("Contact already has an address of that type");
			}
		}

		public void Remove(Int32 addressId)
		{
			foreach (ContactAddress address in this)
			{
				if (address.AddressId == addressId)
				{
					Remove(address);
					break;
				}
			}
		}

		public bool Contains(Int32 addressTypeId)
		{
			foreach (ContactAddress address in this)
			{
				if (address.AddressTypeId == addressTypeId)
				{
					return true;
				}
			}
			return false;
		}

		public bool ContainsDeleted(Int32 addressTypeId)
		{
			foreach (ContactAddress address in DeletedList)
			{
				if (address.AddressTypeId == addressTypeId)
				{
					return true;
				}
			}
			return false;
		}

		#endregion

		#region "Factory Methods"

    internal static ContactAddresses NewContactAddresses()
    {
      return DataPortal.CreateChild<ContactAddresses>();
    }

		internal static ContactAddresses GetContactAddresses(AddressBook.Business.Model.ContactAddress[] data)
    {
      return DataPortal.FetchChild<ContactAddresses>(data);
    }

		private ContactAddresses()
    { /* require use of factory methods */ }

    #endregion

		#region "Data Access"

		private void Child_Fetch(AddressBook.Business.Model.ContactAddress[] data)
		{
			if (data == null) return;

			this.RaiseListChangedEvents = false;

			foreach (var value in data)
			{
				this.Add(ContactAddress.GetAddress(value));
			}

			this.RaiseListChangedEvents = true;
		}

		#endregion
	}
}
